package com.ziyia.a8_3_4;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MainActivity extends AppCompatActivity {

    private EditText title;

    private EditText content;

    private Button save, select;

    private RecyclerView recyclerView;

    private MyDataHelper myDataHelper;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        title = findViewById(R.id.title);
        content = findViewById(R.id.content);
        save = findViewById(R.id.save);
        select = findViewById(R.id.select);
        recyclerView = findViewById(R.id.list);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        myDataHelper = new MyDataHelper(this, "blogs", null, 1);
        myDataHelper.getWritableDatabase();

        // 显示列表
        localData();

        // 保存数据
        save.setOnClickListener(v -> {
            String title = this.title.getText().toString();
            String content = this.content.getText().toString();
            insertData(title, content);
            localData();
        });
    }

    // 弹窗
    public static void alert(Context context, String title, String msg) {
        new AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(msg)
                .create()
                .show();
    }


    // 插入数据
    private void insertData(String title, String content) {
        myDataHelper.getWritableDatabase().execSQL("insert into blog values(null, ?, ?)", new String[]{title, content});
    }

    // 关闭页面的同时，关闭所有 SQLiteDatabase
    @Override
    protected void onDestroy() {
        super.onDestroy();
        myDataHelper.close();
    }

    // 查询数据
    private void localData() {
        SQLiteDatabase database = myDataHelper.getReadableDatabase();
        Cursor blog = database.rawQuery("select * from blog", null);
        inflateRecycler(blog);
    }

    // 显示列表数据
    private void inflateRecycler(Cursor cursor) {
        MyAdapter myAdapter = new MyAdapter(this, cursor, R.layout.item, myDataHelper);
        recyclerView.setAdapter(myAdapter);
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHelper> {
        private Context context;
        private MyDataHelper dataHelper;
        private int resId;
        private List<Map<String, String>> cursorValues = new ArrayList<>();

        public MyAdapter(Context context, Cursor cursor, int resId, MyDataHelper dataHelper) {
            this.context = context;
            this.resId = resId;
            this.dataHelper = dataHelper;

            while (cursor.moveToNext()) {
                Map<String, String> map = new HashMap<>();
                map.put("id", cursor.getString(cursor.getColumnIndex("id")));
                map.put("title", cursor.getString(cursor.getColumnIndex("title")));
                map.put("content", cursor.getString(cursor.getColumnIndex("content")));
                this.cursorValues.add(map);
            }
        }


        class MyViewHelper extends RecyclerView.ViewHolder {
            private TextView title;
            private TextView content;

            public MyViewHelper(@NonNull View itemView) {
                super(itemView);
                title = itemView.findViewById(R.id.title);
                content = itemView.findViewById(R.id.content);

                PopupMenu menu = new PopupMenu(context, title);
                getMenuInflater().inflate(R.menu.popup_menu, menu.getMenu());
                menu.setOnMenuItemClickListener(item -> {
                    int itemId = item.getItemId();
                    SQLiteDatabase database = myDataHelper.getWritableDatabase();
                    Map<String, String> blog = cursorValues.get(getAdapterPosition());
                    switch (itemId) {
                        case R.id.select:
                            String title = blog.get("title");
                            String content = blog.get("content");
                            alert(context, title, content);
                            break;
                        case R.id.delete:
                        database.execSQL("delete from blog where id = ?", new String[]{blog.get("id")});
                        MainActivity.this.localData();
                            break;
                        case R.id.update:
                            alert(context, "menu", "update");
                            break;
                    }
                    return true;
                });
                itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        menu.show();
                        return true;
                    }
                });
            }
        }

        @NonNull
        @Override
        public MyViewHelper onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(resId, parent, false);
            return new MyViewHelper(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHelper holder, int position) {
            Map<String, String> map = cursorValues.get(position);
            holder.title.setText(map.get("title"));
            holder.content.setText(map.get("content"));
        }

        @Override
        public int getItemCount() {
            return cursorValues.size();
        }
    }
}